<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>公众号</title>
</head>
<script src="../js/jquery-2.1.1.min.js"></script>
<script language="javascript">
	var sleepTime = 5;

	$(function() {
		startSocket("localhost:8001")
	});

	/* 
	建立长连接，后台监听
	 */
	function startSocket(ip){
		var websocket = null;
		
		//判断当前浏览器是否支持WebSocket, 主要此处要更换为自己的地址
		if ('WebSocket' in window) {
			websocket = new WebSocket("ws://"+ip+"/socket/wxbiz");
		} else {
			console.log('浏览器不支持');
			startTimeOut();
		}

		//连接发生错误的回调方法
		websocket.onerror = function() {
			console.log("connect error");
			startTimeOut();
		};

		//连接成功建立的回调方法
		websocket.onopen = function(event) {
			console.log("connect success!");
			//setMessageInnerHTML("open");
		}
	
		//接收到消息的回调方法
		websocket.onmessage = function(event) {
			if(event.data == 'run'){
				$("#timedown").show();
				$("#socket").hide();
				$("#taskid").text("开始");
				setTimeout(function() {
					alert("success");
					$("#timedown").hide();
					$("#socket").show();
				}, sleepTime * 1000);
				timeDown("show", sleepTime);
			}
		}
	
		//连接关闭的回调方法
		websocket.onclose = function() {
			console.log("connect close!");
		}
	
		//监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
		window.onbeforeunload = function() {
			websocket.close();
		}

	}
	
	
	//关闭连接
	function closeWebSocket() {
		websocket.close();
	}

	function startTimeOut(){
		alert('exception!')
	}

	/*
   		时间倒计时
   		TimeDown.js
    */
	function timeDown(id, value) {
		//倒计时的总秒数
		var seconds = parseInt(value);
		seconds = seconds.toString().length == 1 ? '0' + seconds : seconds;

		//输出到页面
		document.getElementById(id).innerHTML = seconds;
		//延迟一秒执行自己
		if (parseInt(seconds) - 1 < 0) {

		} else {
			setTimeout(function() {
				timeDown(id, (value - 1));
			}, 1000)
		}

	}

	//生成从minNum到maxNum的随机数
	function randomNum(minNum, maxNum) {
		switch (arguments.length) {
		case 1:
			return parseInt(Math.random() * minNum + 1, 10);
			break;
		case 2:
			return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
			break;
		default:
			return 0;
			break;
		}
	}
</script>
<body>
	<h1>
		剩余任务数：<span id="taskid">0</span>
	</h1>
	<h2 id="timedown">
		阅读刷新中转页面，页面<span id="show"></span>秒后跳转...
	</h2>
	<h2 id="socket" style="display:none;">后台监听中，等待分配任务</h2>
	<a id="biza" target="_black" href='#'>
		
	</a>
</body>
</html>